package cn.neo.support.smartadapters.builders;

import android.content.Context;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.ViewGroup;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import cn.neo.support.smartadapters.utils.Mapper;
import cn.neo.support.smartadapters.utils.Reflections;
import cn.neo.support.smartadapters.views.BindableLayout;


/**
 * Specific layout builder for Android Annotations @EViewGroup annotated classes.
 * <p/>
 * Those classes are build by calling a static build(Context) method so that's what we need to do
 * in order to create properly those elements.
 */
public class AABindableLayoutBuilder extends DefaultBindableLayoutBuilder {

    @Override
    public View build(
            @NonNull ViewGroup parent, int viewType, Object item, @NonNull Mapper mapper) {
        Class<? extends BindableLayout> viewClass = mapper.viewClassFromViewType(viewType);
        if (viewClass == null) {
            throw new IllegalArgumentException("viewType not present in the mapper");
        }
        try {
            Method method = Reflections.method(viewClass, "build", Context.class);
            return (ViewGroup) method.invoke(null, parent.getContext());
        } catch (NoSuchMethodException e) {
            throw new IllegalArgumentException("View class is not a @EViewGroup generated by AndroidAnnotations", e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException("Invocation Target", e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("Illegal Access ", e);
        }
    }
}